package shop.up;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * CompletableFuture 异步编排 {@link CompletableFutureDemo}
 *
 * @author Kevin
 * @date 2022/7/12
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*
         * runAsync 异步操作，无返回值
         * supplyAsync 异步操作，有返回值
         * whenComplete 计算完成后的回调方法
         * exceptionally 出现异常后的回调方法
         * thenApply 串行化执行
         */
        CompletableFuture future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            // int i = 10 / 0;
            return 200;
        }).thenApply(o -> {
            System.out.println("thenApply方法，上次返回结果：o=" + o);
            return  o * 2;
        }).whenComplete((o, throwable) -> { // 处理正常或异常的计算结果
            // o 表示上一步执行完成的返回值
            System.out.println("---whenComplete方法，上一步返回结果：o=" + o);
            System.out.println("---throwable1=" + throwable);
        }).exceptionally((throwable) -> { // 处理异常情况
            System.out.println("---throwable2=" + throwable);
            return 404;
        });

        // 获取返回值
        System.out.println(future.get());
    }
}
